package com.larry.tinyweb.core;


import com.larry.tinyweb.plugin.PluginManager;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by larry on 16/8/14.
 */
public class GlobalFilter implements Filter {
    private Router actionRouter;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Global.contextPath = filterConfig.getServletContext().getContextPath();
        actionRouter = new ActionRouter();
        TinyWeb.start();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        request.setCharacterEncoding("utf-8");
        // 封装请求到RequestEntity
        RequestEntity requestEntity  = RequestEntity.getEntity(request, response);
        try {
            // 插件处理
            PluginManager.doPlugin(requestEntity);
            // action路由
            if (!requestEntity.hasRoute()) actionRouter.route(requestEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 如果是普通的文件请求
        if (!requestEntity.hasRoute()) filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
